package com.atguigu.vod.service.impl;

import com.aliyun.vod.upload.impl.UploadVideoImpl;
import com.aliyun.vod.upload.req.UploadStreamRequest;
import com.aliyun.vod.upload.resp.UploadStreamResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.vod.model.v20170321.DeleteVideoRequest;
import com.aliyuncs.vod.model.v20170321.DeleteVideoResponse;
import com.atguigu.commonutils.R;
import com.atguigu.vod.service.VodService;
import com.atguigu.vod.utils.ConstantVodUtils;
import com.atguigu.vod.utils.InitObject;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

@Service
public class VodServiceImpl implements VodService {

    @Override
    public String uploadVideo(MultipartFile file) {
        String accessKeyId = ConstantVodUtils.KEY_ID;
        String accessKeySecret = ConstantVodUtils.KEY_SECRET;
        String fileName = file.getOriginalFilename();
        String title = fileName.substring(0, fileName.lastIndexOf("."));
        InputStream inputStream = null;
        try {
            inputStream = file.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        /**
         * accessKeyId:     秘钥ID
         * accessKeySecret:     密码
         * title:  文件在阿里云中保存的名称
         * filename:    上传文件原始名称
         * inputStream:     文件流
         * */
        UploadStreamRequest request = new UploadStreamRequest(accessKeyId, accessKeySecret, title, fileName, inputStream);

        String videoId = null;
        UploadVideoImpl uploader = new UploadVideoImpl();
        UploadStreamResponse response = uploader.uploadStream(request);
        System.out.print("RequestId=" + response.getRequestId() + "\n");  //请求视频点播服务的请求ID
        if (response.isSuccess()) {
            videoId = response.getVideoId();
        } else { //如果设置回调URL无效，不影响视频上传，可以返回VideoId同时会返回错误码。其他情况上传失败时，VideoId为空，此时需要根据返回错误码分析具体错误原因
            videoId = response.getVideoId();
        }
        return videoId;
    }

    @Override
    public void deleteBenchVideo(List videoIdList) {
        String accessKeyId = ConstantVodUtils.KEY_ID;
        String accessKeySecret = ConstantVodUtils.KEY_SECRET;
        DefaultAcsClient client = null;
        //转换videoIdList的值
        String videos = StringUtils.join(videoIdList.toArray(), ",");
        try {
            client = InitObject.initVodClient(accessKeyId, accessKeySecret);
            DeleteVideoRequest request = new DeleteVideoRequest();
            request.setVideoIds(videos);
            client.getAcsResponse(request);

        } catch (ClientException e) {
            e.printStackTrace();
            try {
                throw new Exception("删除视频失败");
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }


}
